package cn.stylefeng.guns.sys.modular.system.service.impl;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.consts.ConstantsContext;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfos;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.ExcelFormatUtil;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.controller.BaseFrontController;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyBrandMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyContractDetailMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyContractMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyContractOrtherDetailMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyContractParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyContractResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyContractDetailService;
import cn.stylefeng.guns.sys.modular.system.service.BtyContractOrtherDetailService;
import  cn.stylefeng.guns.sys.modular.system.service.BtyContractService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 合同管理 服务实现类
 * </p>
 *
 * @author liuy
 * @since 2022-05-10
 */
@Service
@Slf4j
public class BtyContractServiceImpl extends ServiceImpl<BtyContractMapper, BtyContract> implements BtyContractService {
    @Resource
    private BtyContractDetailService detailService;
    @Resource
    private BtyContractDetailMapper detailMapper;
    @Resource
    private BtyContractOrtherDetailService otherDetailService;

    @Resource
    private BtyContractOrtherDetailMapper otherDetailMapper;
    @Resource
    private BtyBrandMapper brandMapper;

    @Override
    public Integer add(BtyContractParam param){
        BtyContract entity = getEntity(param);
        //根据店名获取妖码
        String dm=param.getDm()==null?"":param.getDm();
        String yaoma="";
        String cwm="";
        BtyBrand brand=brandMapper.selectOne(new QueryWrapper<BtyBrand>().eq("dm",dm));
        if(ToolUtil.isNotEmpty(brand)){
            yaoma=brand.getYaoma();
            cwm=brand.getCwm();
            entity.setCwm(cwm);
            entity.setYaoma(yaoma);
        }
        //根据店名获取开发人员信息
        List<BtyContractResult>kfry=baseMapper.kfry(dm);
        if(kfry.size()>0){
           entity.setDeveloper(kfry.get(0).getDeveloper());
           entity.setPhone(kfry.get(0).getPhone());
        }
        this.save(entity);
        List<BtyContractDetail> list=param.getDetailList();
        List<BtyContractOrtherDetail>otherDetailList=param.getOtherDetailList();
        if(ToolUtil.isNotEmpty(list)&&list.size()>0){
            for (BtyContractDetail detail : list) {
                detail.setContractId(entity.getId());
                detailService.save(detail);
            }
        }
        if(ToolUtil.isNotEmpty(otherDetailList)&&otherDetailList.size()>0) {
            for (BtyContractOrtherDetail otherDetail : otherDetailList) {
                otherDetail.setContractId(entity.getId());
                otherDetailService.save(otherDetail);
            }
        }
        baseMapper.saveArea();
        Integer id=entity.getId();
        return  id;
    }

    @Override
    public void delete(BtyContractParam param){
        this.removeById(getKey(param));
        detailMapper.delete(new QueryWrapper<BtyContractDetail>().eq("contract_id",param.getId()));
        otherDetailMapper.delete(new QueryWrapper<BtyContractOrtherDetail>().eq("contract_id",param.getId()));
    }

    @Override
    public void update(BtyContractParam param){
        BtyContract oldEntity = getOldEntity(param);
        BtyContract newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);

        List<BtyContractDetail> list=param.getDetailList();
        if(ToolUtil.isNotEmpty(param.getDetailList())&&param.getDetailList().size()>0) {
            detailMapper.delete(new QueryWrapper<BtyContractDetail>().eq("contract_id",newEntity.getId()));
            for (BtyContractDetail detail : list) {
                detailService.save(detail);
            }
        }

        List<BtyContractOrtherDetail>otherDetailList=param.getOtherDetailList();
        if(ToolUtil.isNotEmpty(param.getOtherDetailList())&&param.getOtherDetailList().size()>0) {
            otherDetailMapper.delete(new QueryWrapper<BtyContractOrtherDetail>().eq("contract_id",newEntity.getId()));
            for (BtyContractOrtherDetail otherDetail : otherDetailList) {
                otherDetailService.save(otherDetail);
            }
        }
    }

    @Override
    public BtyContractResult findBySpec(BtyContractParam param){
        return null;
    }

    @Override
    public List<BtyContractResult> findListBySpec(BtyContractParam param) throws ParseException {
        if(ToolUtil.isNotEmpty(param.getEndTime())&&param.getEndTime().contains("|")){
            String[] split = param.getEndTime().split("|");
            param.setBeginTime(split[0]);
            param.setEndTime(split[1]);
        }
        List<String> dmList=new ArrayList<>();

        if(ToolUtil.isNotEmpty(param.getDm())&&param.getDm().contains(",")){
            String[] split = param.getDm().split(",");
            for (String s : split) {
                dmList.add(s);
            }
        }
        param.setList(dmList);
        List<BtyContractResult> list=baseMapper.customList(param);
        for (BtyContractResult result : list) {
            if(ToolUtil.isNotEmpty(result.getEndTime())&&result.getEndTime().length()==10){
                String  endTime=result.getEndTime().replaceAll("\\s*", "");
                long days= DateUtil.getDaysNum(DateUtil.getNowDate(),endTime);
                result.setDays(days);
            }
            //根据id获取合同管理详情
            List<BtyContractDetail>detailList=detailService.list(new QueryWrapper<BtyContractDetail>().eq("contract_id",result.getId()));
            result.setDetailList(detailList);
            List<BtyContractOrtherDetail>ortherDetails=otherDetailService.list(new QueryWrapper<BtyContractOrtherDetail>().eq("contract_id",result.getId()));
            result.setOtherDetailList(ortherDetails);

        }
        return list;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyContractParam param) throws ParseException {
       //工程开发人员
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        String username=LoginContextHolder.getContext().getUser().getName();
        if(roleNames.contains("工程开发人员")){
           param.setKfry(username);
        }
        if(username.equals("初军军")|username.equals("丁玲")|username.equals("于婷婷")|username.equals("丁飞")|roleNames.contains("开发总监")|username.equals("张元国")){

        }else if(roleNames.contains("成本会计")){
            param.setCbkj(username);
        }
        if(ToolUtil.isNotEmpty(param.getEndTime())&&param.getEndTime().contains("|")){
            String[] split = param.getEndTime().split("|");
            param.setBeginTime(split[0]);
            param.setEndTime(split[1]);
        }
        List<String> dmList=new ArrayList<>();

        if(ToolUtil.isNotEmpty(param.getDm())&&param.getDm().contains(",")){
            String[] split = param.getDm().split(",");
            for (String s : split) {
                dmList.add(s);
            }
        }
        param.setList(dmList);




        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        List<BtyContractResult> list=page.getRecords();
        for (BtyContractResult result : list) {
             if(ToolUtil.isNotEmpty(result.getEndTime())&&result.getEndTime().length()==10){
                 String  endTime=result.getEndTime().replaceAll("\\s*", "");
                 long days= DateUtil.getDaysNum(DateUtil.getNowDate(),endTime);
                 result.setDays(days);
             }

            //根据id获取合同管理详情
            List<BtyContractDetail>detailList=detailService.list(new QueryWrapper<BtyContractDetail>().eq("contract_id",result.getId()));
            result.setDetailList(detailList);
            List<BtyContractOrtherDetail>ortherDetails=otherDetailService.list(new QueryWrapper<BtyContractOrtherDetail>().eq("contract_id",result.getId()));
            result.setOtherDetailList(ortherDetails);

        }
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public List<Map> kfryList() {
        return baseMapper.kfryList();
    }

    @Override
    public List<Map> primaryAreaList() {
        return baseMapper.primaryAreaList();
    }

    @Override
    public List<Map> secondaryAreaList(int pid) {
        return baseMapper.secondaryAreaList(pid);
    }

    @Override
    public List<Map> dmList() {
        return baseMapper.dmList();
    }

    @Override
    public boolean insertContract(List<BtyContract> list) {
        return false;
    }

    @Override
    public List<BtyContractResult> kfry(String dm) {
        return baseMapper.kfry(dm);
    }

    @Override
    public Boolean batchImport(String fileName, MultipartFile file, BtyContractParam btyElmsxfParam) throws Exception {
        boolean notNull = false;
            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                throw new Exception("上传文件格式不正确");
            }
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }

            for (int i = 0; i < 1; i++) {
                //Sheet sheet = wb.getSheetAt(i);
                Sheet sheet = wb.getSheetAt(0);
                if (sheet != null) {
                    notNull = true;
                }

                int lastRowNum = sheet.getLastRowNum();
                for (int r = 1; r <= lastRowNum; r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    //获取单元格
                    for(int m=1;m<24;m++){
                        Cell cell = row.getCell(m);
                        if (ToolUtil.isNotEmpty(cell)) {
                            cell.setCellType(CellType.STRING);
                        }
                    }
                    //门店id

                    //String mdid=row.getCell(0) == null ? "" : row.getCell(0).getStringCellValue();
                    //一级区域
                    String yjqy = row.getCell(1) == null ? "" : row.getCell(1).getStringCellValue();
                    //二级区域
                    String ejqy = row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue();
                    //财务码
                    String cwm = row.getCell(3) == null ? "" : row.getCell(3).getStringCellValue();
                    String yaoma = row.getCell(4) == null ? "" : row.getCell(4).getStringCellValue();
                    //店名
                    String dm = row.getCell(5) == null ?"" : row.getCell(5).getStringCellValue();
                    //合同是否收回
                    String sfsh=row.getCell(6) == null ? "" : row.getCell(6).getStringCellValue();
                    int state=0;
                    //1已收回 2未收回 3复印件 4电子版 5无 6合同不全
                    if(sfsh.equals("已收回")){
                        state=1;
                    }else if(sfsh.equals("未收回")){
                        state=2;
                    }else if(sfsh.equals("复印件")){
                        state=3;
                    }else if(sfsh.equals("电子版")){
                        state=4;
                    }else if(sfsh.equals("无")){
                        state=5;
                    }else if(sfsh.equals("合同不全")){
                        state=6;
                    }
                    //合同备注
                    String htbz=row.getCell(7) == null ? "" : row.getCell(7).getStringCellValue();
                    //甲方
                    String jf=row.getCell(8) == null ? "" : row.getCell(8).getStringCellValue();
                    //乙方
                    String yf=row.getCell(9) == null ? "" : row.getCell(9).getStringCellValue();
                    //开发人员
                    String kfry=row.getCell(10) == null ? "" : row.getCell(10).getStringCellValue();
                    //开发人员电话
                    String phone=row.getCell(11) == null ? "" : row.getCell(11).getStringCellValue();
                    //开业时间
                    String kysj = row.getCell(12) == null ? "" : row.getCell(12).getStringCellValue();
                    if(kysj.contains(".")){
                        kysj=kysj.replace(".","-");
                    }
                    //面积
                    String mj = row.getCell(13) == null? "" : row.getCell(13).getStringCellValue();
                    //起租时间
                    String qzsj = row.getCell(14) == null ? "" : row.getCell(14).getStringCellValue();
                    if(qzsj.contains(".")){
                        qzsj=qzsj.replace(".","-");
                    }
                    //到期时间
                    String dqsj = row.getCell(15) == null ? "" : row.getCell(15).getStringCellValue();
                    if(dqsj.contains(".")){
                        dqsj=dqsj.replace(".","-");
                    }
                    String sqzj = row.getCell(16) == null ? "" : row.getCell(16).getStringCellValue();
                    String sqwyf = row.getCell(17) == null ? "" : row.getCell(17).getStringCellValue();
                    String zjjnzq = row.getCell(18) == null ? "" : row.getCell(18).getStringCellValue();
                    String dzmx = row.getCell(19) == null ? "" : row.getCell(19).getStringCellValue();
                    if(dzmx.contains(".")){
                        dzmx=dzmx.replace(".","-");
                    }
                    //抽成租金
                    String cczj = row.getCell(20) == null ? "" : row.getCell(20).getStringCellValue();
                    //其它费用
                    String qtfy = row.getCell(21) == null ? "" : row.getCell(21).getStringCellValue();
                    //保证金
                    String bzj = row.getCell(22) == null ? "" : row.getCell(22).getStringCellValue();
                    String bz = row.getCell(23) == null ? "" : row.getCell(23).getStringCellValue();

                    if (ToolUtil.isNotEmpty(dqsj) && !dqsj.contains("-")&&!dqsj.contains("/")){
                        Calendar calendar = new GregorianCalendar(1900,0,-1);
                        Date d = calendar.getTime();
                        Date date = DateUtils.addDays(d, Integer.valueOf(dqsj));
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        dqsj = simpleDateFormat.format(date);
                    }

                    if (ToolUtil.isNotEmpty(kysj) && !kysj.contains("-")&&!kysj.contains("/")){
                        Calendar calendar = new GregorianCalendar(1900,0,-1);
                        Date d = calendar.getTime();
                        Date date = DateUtils.addDays(d, Integer.valueOf(kysj));
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        kysj = simpleDateFormat.format(date);
                    }

                    if (ToolUtil.isNotEmpty(qzsj) && !qzsj.contains("-")&&!qzsj.contains("/")){
                        Calendar calendar = new GregorianCalendar(1900,0,-1);
                        Date d = calendar.getTime();
                        Date date = DateUtils.addDays(d, Integer.valueOf(qzsj));
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        qzsj = simpleDateFormat.format(date);
                    }

                    int flag=0;
                    //租金缴纳周期1月付 2俩月付 3季付 4半年付 5年付
                    if(zjjnzq.equals("月付")){
                        flag=1;
                    }else if(zjjnzq.contains("俩月")){
                        flag=2;
                    }else if(zjjnzq.equals("季付")){
                        flag=3;
                    }else if(zjjnzq.equals("半年付")){
                        flag=4;
                    }else if(zjjnzq.equals("年付")){
                        flag=5;
                    }
                    BtyContract contracts=baseMapper.selectOne(new QueryWrapper<BtyContract>().eq("yaoma",yaoma));
                    if(ToolUtil.isNotEmpty(contracts)){
                        contracts.setCwm(cwm);
                        contracts.setYaoma(yaoma);
                        contracts.setDm(dm);
                        contracts.setState(state);
                        contracts.setContractRemarks(htbz);
                        contracts.setFirstParty(jf);
                        contracts.setSecondParty(yf);
                        contracts.setDeveloper(kfry);
                        contracts.setPhone(phone);
                        contracts.setOpenDate(kysj);
                        if(!mj.equals("/")){
                            contracts.setArea(new BigDecimal(mj).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                        contracts.setStartTime(qzsj);
                        contracts.setEndTime(dqsj.replace("/","").replaceAll("\\s*", ""));
                        if(!sqzj.equals("/")) {
                            contracts.setFirstMonthlyRent(new BigDecimal(sqzj).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                        if(!sqwyf.equals("/")) {
                            contracts.setFirstMonthlyPropertyFee(new BigDecimal(sqwyf).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                        contracts.setRentPaymentCycle(flag);
                        contracts.setDetailRemark(dzmx);
                        contracts.setRemark(bz);
                        //租金备注
                        contracts.setRentRemark(cczj);
                        //其它费用备注
                        contracts.setCostRemark(qtfy);
                        //保证金备注
                        contracts.setBondRemark(bzj);
                        baseMapper.updateById(contracts);
                    }else {
                        BtyContract contract = new BtyContract();
                        //contract.setPrimaryArea(yjqy);
                        //contract.setPid();
                        //contract.setSecondaryArea(ejqy);
                        contract.setCwm(cwm);
                        contract.setYaoma(yaoma);
                        contract.setDm(dm);
                        contract.setState(state);
                        contract.setContractRemarks(htbz);
                        contract.setFirstParty(jf);
                        contract.setSecondParty(yf);
                        contract.setDeveloper(kfry);
                        contract.setPhone(phone);
                        contract.setOpenDate(kysj);
                        if (!mj.equals("/")) {
                            contract.setArea(new BigDecimal(mj).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                        contract.setStartTime(qzsj);
                        contract.setEndTime(dqsj.replace("/", "").replaceAll("\\s*", ""));
                        if (!sqzj.equals("/")) {
                            contract.setFirstMonthlyRent(new BigDecimal(sqzj).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                        if (!sqwyf.equals("/")) {
                            contract.setFirstMonthlyPropertyFee(new BigDecimal(sqwyf).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                        contract.setRentPaymentCycle(flag);
                        contract.setDetailRemark(dzmx);
                        contract.setRemark(bz);
                        //租金备注
                        contract.setRentRemark(cczj);
                        //其它费用备注
                        contract.setCostRemark(qtfy);
                        //保证金备注
                        contract.setBondRemark(bzj);
                        this.save(contract);
                    }
                }
                baseMapper.saveArea();
            }
            return  notNull;
    }

    @Override
    public ResponseEntity<byte[]> exportMx(HttpServletRequest request, HttpServletResponse response, BtyContractParam param) {
        try {
            List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
            String username=LoginContextHolder.getContext().getUser().getName();
            if(roleNames.contains("工程开发人员")){
                param.setKfry(username);
            }
            if(username.equals("初军军")|username.equals("丁玲")|username.equals("于婷婷")|username.equals("丁飞")){

            }else if(roleNames.contains("成本会计")){
                param.setCbkj(username);
            }
            String timestamp=DateUtil.getStampNow();
            String fileName ="合同管理"+timestamp;
            //获取明细列表
            if(ToolUtil.isNotEmpty(param.getDeveloper())&&param.getDeveloper().equals("全部")){
                param.setDeveloper(null);
            }
           List<BtyContractResult>list=baseMapper.customList(param);
            for (BtyContractResult result : list) {
                List<BtyContractDetail>detailList=detailMapper.selectList(new QueryWrapper<BtyContractDetail>().eq("contract_id",result.getId()));
                if(detailList.size()>0){
                    StringBuilder sb=new StringBuilder();
                    for (BtyContractDetail detail : detailList) {
                        String expenseName=detail.getExpenseName()==null?"":detail.getExpenseName();
                        String fymc="";
                        //1房租  2 物业费 3 运营管理费 4 推广费 5 其它
                        if(expenseName.equals("1")){
                            fymc="房租";
                        }
                        if(expenseName.equals("2")){
                            fymc="物业费";
                        }
                        if(expenseName.equals("3")){
                            fymc="运营管理费";
                        }
                        if(expenseName.equals("4")){
                            fymc="推广费";
                        }
                        if(expenseName.equals("5")){
                            fymc=detail.getOtherExpensesName();
                        }
                        String detailDate=detail.getDetailDate();
                        detailDate=detailDate.replace("[","").replace("]","").replace(",","-").replace("\"","");
                        //计费方式1每日每平 2每月每平 3固定计费
                        Integer flag=  detail.getBillingMethod();
                        String jffs="";
                        if(flag==1){
                            jffs="每日每平";
                        }
                        if(flag==2){
                            jffs="每月每平";
                        }
                        if(flag==3){
                            jffs="固定计费";
                        }
                        BigDecimal dailyAverageAmount =detail.getDailyAverageAmount();
                        BigDecimal monthlyAmount=detail.getMonthlyAmount();
                        BigDecimal totalAmount=detail.getTotalAmount();
                        sb.append(fymc+":").append(detailDate).append(jffs).append(":").append(dailyAverageAmount).append("月金额:").append(monthlyAmount).append("总金额:").append(totalAmount).append("\r\n");
                    }
                     result.setDzmx(sb.toString());
                    System.out.println("sb:"+sb);

                }
                List<BtyContractOrtherDetail>otherDetailList=otherDetailMapper.selectList(new QueryWrapper<BtyContractOrtherDetail>().eq("contract_id",result.getId()));
                if(otherDetailList.size()>0) {
                    StringBuilder sb2 = new StringBuilder();
                    StringBuilder sb3 = new StringBuilder();
                    StringBuilder sb4 = new StringBuilder();
                    for (BtyContractOrtherDetail otherDetail : otherDetailList) {
                        String typeName = "";
                        Integer type = otherDetail.getType();
                        String title = otherDetail.getTitle();
                        String content = otherDetail.getContent();
                        //1 抽成租金 2其他费用 3 保证金
                        if (type == 1) {
                            typeName = "抽成租金";
                            sb2.append(title.replace("|", "-")).append(",").append(content);
                        }
                        if (type == 2) {
                            typeName = "其他费用";
                            sb3.append(title).append(content);
                        }
                        if (type == 3) {
                            typeName = "保证金";
                            sb4.append(title).append(content);
                        }
                    }
                    result.setRentBonus(sb2.toString());
                    result.setOtherExpensesName(sb3.toString());
                    result.setBondName(sb4.toString());
                }
            }

            InputStream stream = exportHandler(list, fileName);
            return new BaseFrontController().buildResponseEntity(stream, fileName + ".xlsx");
        } catch (Exception e) {
            e.printStackTrace();
            //logger.error("导出明细异常：{}", e.getMessage());
        }
        return null;
    }

    private InputStream exportHandler(List<BtyContractResult>list ,String name){
        log.info("exportHandler start...");

        ByteArrayOutputStream out=null;
        InputStream is=null;

        // 保留1000条数据在内存中
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        SXSSFSheet sheet = wb.createSheet();
        //报表样式
        CellStyle contentStyle = ExcelFormatUtil.contentStyle(wb);

        //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
        int firstRow = 1;
        int lastRow = 1;
        int firstCol = 1;
        int lastCol = 23;

        //SXSSFRow row1 = sheet.createRow(0);
        //row1.setHeight((short)600);
        //SXSSFCell cell0 = row1.createCell(0);
        //sheet.addMergedRegion(new CellRangeAddress(0,0,0,lastCol-1));
//        cell0.setCellValue(name);
//        cell0.setCellStyle(ExcelFormatUtil.titleSytle(wb));

        //设置内容标题
        /**
         * rentRemark 租金备注 costRemark 其它费用备注   bondRemark 保证金备注
         */
        int contentTitleStartRow = 1;
        String[] titles=new String[]{"序号","一级区域","二级区域","财务码","妖码","门店","合同是否收回","合同备注","是否营业","甲方","乙方","开发人员","开发人员电话","开业时间","面积㎡","起租时间","到期时间","首期月租金(元)","首期月物业费(元)","租金缴纳周期","缴纳周期备注","递增明细","抽成租金","其他费用","保证金","备注"};
        // 字段名所在表格的宽度，数量应与列字段名数量一致
        int[] withs = new int[]{2500, 5000, 5000, 5000, 5000, 5200, 5000, 5000, 5000,5000,5000,5000,5000,5000, 5000, 5000,5000,5000,5000,5000,5000, 5000, 5000,5000,5000,5000};
        // 设置报表头样式,cell样式
        CellStyle headSytle = ExcelFormatUtil.headSytle(wb);
        ExcelFormatUtil.initContentTitleEX(sheet,headSytle,contentTitleStartRow,titles,withs);


        int contentStartRow = 2;

        for(int i=0;i<list.size();i++){
            BtyContractResult mx=list.get(i);
            SXSSFRow row = sheet.createRow(contentStartRow+i-1);
            int j=0;
            SXSSFCell xh = row.createCell(j++);//xuhao
            xh.setCellStyle(contentStyle);
            xh.setCellValue(i+1);

            SXSSFCell cell = row.createCell(j++);//一级区域
            cell.setCellValue(mx.getPrimaryArea()!=null?mx.getPrimaryArea():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//二级区域
            cell.setCellValue(mx.getSecondaryArea()!=null?mx.getSecondaryArea():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//财务码
            cell.setCellValue(mx.getCwm()!=null?mx.getCwm():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//妖码
            cell.setCellValue(mx.getYaoma()!=null?mx.getYaoma():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//门店
            cell.setCellValue(mx.getDm()!=null?mx.getDm():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//合同是否收回
            Integer state=mx.getState()==null?0:mx.getState();
            String  stateName="";
            //1已收回 2未收回 3复印件 4电子版 5无 6合同不全
            if (state == 1) {
                stateName = "已收回";
            }
            if (state == 2) {
                stateName = "未收回 ";
            }
            if (state == 3) {
                stateName = "复印件";
            }
            if (state == 4) {
                stateName = "电子版";
            }
            if (state == 5) {
                stateName = "无";
            }
            if (state == 6) {
                stateName = "合同不全";
            }
            cell.setCellValue(stateName);
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//合同备注
            cell.setCellValue(mx.getContractRemarks()!=null?mx.getContractRemarks():"");
            cell.setCellStyle(contentStyle);

            Integer openState=mx.getOpenState()==null?0:mx.getOpenState();
            String  openStateName="";
            //营业状态 1 营业中 2 已闭店
            if (openState == 1) {
                openStateName = "营业中";
            }
            if (openState == 2) {
                openStateName = "已闭店 ";
            }

            cell = row.createCell(j++);//是否营业
            cell.setCellValue(openStateName);
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//甲方
            cell.setCellValue(mx.getFirstParty()!=null?mx.getFirstParty():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//乙方
            cell.setCellValue(mx.getSecondParty()!=null?mx.getSecondParty():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//开发人员
            cell.setCellValue(mx.getDeveloper()!=null?mx.getDeveloper():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//开发人员电话
            cell.setCellValue(mx.getPhone()!=null?mx.getPhone():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//开业时间
            cell.setCellValue(mx.getOpenDate()!=null?mx.getOpenDate():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//面积
            cell.setCellValue(mx.getArea()!=null?mx.getArea().toString():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//起租时间
            cell.setCellValue(mx.getStartTime()!=null?mx.getStartTime():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//到期时间
            cell.setCellValue(mx.getEndTime()!=null?mx.getEndTime():"");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//首期月租金
            cell.setCellValue(mx.getFirstMonthlyRent()!=null?mx.getFirstMonthlyRent().toString():"0");
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//首期月物业费
            cell.setCellValue(mx.getFirstMonthlyPropertyFee()!=null?mx.getFirstMonthlyPropertyFee().toString():"0");
            cell.setCellStyle(contentStyle);

            Integer flag=mx.getRentPaymentCycle()==null?0:mx.getRentPaymentCycle();
            String  flagName="";
            //租金缴纳周期1月付 2俩月付 3季付 4半年付 5年付
            if (flag == 1) {
                flagName = "月付";
            }
            if (flag == 2) {
                flagName = "俩月付 ";
            }
            if (flag == 3) {
                flagName = "季付";
            }
            if (flag == 4) {
                flagName = "半年付";
            }
            if (flag == 5) {
                flagName = "年付";
            }
            cell = row.createCell(j++);//租金缴纳周期
            cell.setCellValue(flagName);
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//租金缴纳周期备注
            cell.setCellValue(mx.getRentPaymentRemark()!=null?mx.getRentPaymentRemark():mx.getRentPaymentRemark());
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//递增明细
            cell.setCellValue(mx.getDzmx()!=null?mx.getDzmx():mx.getDetailRemark());
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//抽成租金
            cell.setCellValue(mx.getRentBonus()!=null?mx.getRentBonus():mx.getRentRemark());
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//其它费用
            cell.setCellValue(mx.getOtherExpensesName()!=null?mx.getOtherExpensesName():mx.getCostRemark());
            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//保证金
            cell.setCellValue(mx.getBondName()!=null?mx.getBondName():mx.getBondRemark());
            cell.setCellStyle(contentStyle);

//            cell = row.createCell(j++);//递增明细备注
//            cell.setCellValue(mx.getDetailRemark()!=null?mx.getDetailRemark():"");
//            cell.setCellStyle(contentStyle);
//
//            cell = row.createCell(j++);//租金备注
//            cell.setCellValue(mx.getRentRemark()!=null?mx.getRentRemark():"");
//            cell.setCellStyle(contentStyle);
//
//            cell = row.createCell(j++);//其它费用备注
//            cell.setCellValue(mx.getCostRemark()!=null?mx.getCostRemark():"");
//            cell.setCellStyle(contentStyle);
//
//            cell = row.createCell(j++);//保证金备注
//            cell.setCellValue(mx.getBondRemark()!=null?mx.getBondRemark():"");
//            cell.setCellStyle(contentStyle);

            cell = row.createCell(j++);//备注
            cell.setCellValue(mx.getRemark()!=null?mx.getRemark():"");
            cell.setCellStyle(contentStyle);

        }

        try {
            out = new ByteArrayOutputStream();
            wb.write(out);
            is=new ByteArrayInputStream(out.toByteArray());
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(out!=null){
                    out.close();
                }
                if(is!=null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.info("exportHandler end...");
        return is;
    }

    private Serializable getKey(BtyContractParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyContract getOldEntity(BtyContractParam param) {
        return this.getById(getKey(param));
    }

    private BtyContract getEntity(BtyContractParam param) {
        BtyContract entity = new BtyContract();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
